package storage.file;

import java.nio.ByteBuffer;
import java.nio.charset.Charset;

import server.starDB;

public class Page {
    public static final int BLOCK_SIZE = 400;

    public static final int INT_SIZE = 4;
    
    public static final int STR_SIZE(int n) {
    	double bytesPerChar = Charset.defaultCharset().newEncoder().maxBytesPerChar();
    	return INT_SIZE + n * (int)bytesPerChar;
    }
    
    private ByteBuffer contents = ByteBuffer.allocateDirect(BLOCK_SIZE);
    private FileMgr filemgr = starDB.fileMgr();
    
    public Page() {}
    
    public synchronized void read(Block blk) {
    	filemgr.read(blk, contents);
    }
    
    public synchronized void write(Block blk) {
        filemgr.write(blk, contents);
    }
    
    public synchronized Block append(String filename) {
        return filemgr.append(filename, contents);
    }
    
    public synchronized int getInt(int offset) {
        contents.position(offset);
        return contents.getInt();
    }
    
    public synchronized void setInt(int offset, int val) {
        contents.position(offset);
        contents.putInt(val);
    }
    
    public synchronized String getString(int offset) {
        contents.position(offset);
        int len = contents.getInt();
        byte[] byteval = new byte[len];
        contents.get(byteval);
        return new String(byteval);
    }
    
    public synchronized void setString(int offset, String val) {
        contents.position(offset);
        byte[] byteval = val.getBytes();
        contents.putInt(byteval.length);
        contents.put(byteval);
    }
    
}
